package com.yupi.yoj.controller;

import cn.hutool.json.JSONUtil;
import com.yupi.yoj.annotation.AuthCheck;
import com.yupi.yoj.common.BaseResponse;
import com.yupi.yoj.common.DeleteRequest;
import com.yupi.yoj.common.ErrorCode;
import com.yupi.yoj.common.ResultUtils;
import com.yupi.yoj.constant.QueueConstant;
import com.yupi.yoj.constant.UserConstant;
import com.yupi.yoj.exception.BusinessException;
import com.yupi.yoj.exception.ThrowUtils;
import com.yupi.yoj.model.dto.contestuser.ContestUserAddRequest;
import com.yupi.yoj.model.dto.contestuser.ContestUserJoinRequest;
import com.yupi.yoj.model.dto.contestuser.ContestUserUpdateRequest;
import com.yupi.yoj.model.dto.contestuser.ContestUserUpdateSubidsRequest;
import com.yupi.yoj.model.entity.ContestUser;
import com.yupi.yoj.model.vo.ContestUserVO;
import com.yupi.yoj.model.vo.ContestVO;
import com.yupi.yoj.service.ContestUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 帖子接口
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://yupi.icu">编程导航知识星球</a>
 */
@RequestMapping("/contestUser")
@RestController
@Slf4j
public class ContestUserController {

    @Resource
    private ContestUserService contestUserService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // region 增删改查

    /**
     * 创建
     *
     * @param contestUserAddRequest
     * @return
     */
    @PostMapping("/add")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Long> addContestUser(@RequestBody ContestUserAddRequest contestUserAddRequest) {
        if (contestUserAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long contestid = contestUserAddRequest.getContestid();
        Long userid = contestUserAddRequest.getUserid();
        List<Long> subids = contestUserAddRequest.getSubids();

        ThrowUtils.throwIf(contestid <= 0 || userid <= 0 , ErrorCode.PARAMS_ERROR, "参数错误");

        ContestUser contestUser = new ContestUser();
        BeanUtils.copyProperties(contestUserAddRequest, contestUser);

        // 提交列表
        if (subids != null) {
            contestUser.setSubids(JSONUtil.toJsonStr(subids));
        }

        boolean result = contestUserService.save(contestUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newContestUserId = contestUser.getId();
        // 将比赛发布消息传入消息队列
        rabbitTemplate.convertAndSend(QueueConstant.QUEUE_COMPUTE_CONTEST, newContestUserId);

        return ResultUtils.success(newContestUserId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteContestUser(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        // 判断是否存在
        ContestUser oldContestUser = contestUserService.getById(id);
        ThrowUtils.throwIf(oldContestUser == null, ErrorCode.NOT_FOUND_ERROR);

        boolean b = contestUserService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param contestUserUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateContestUser(@RequestBody ContestUserUpdateRequest contestUserUpdateRequest) {
        if (contestUserUpdateRequest == null || contestUserUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        ContestUser contestUser = new ContestUser();
        BeanUtils.copyProperties(contestUserUpdateRequest, contestUser);
        List<Long> subids = contestUserUpdateRequest.getSubids();
        // 提交列表
        if (subids != null) {
            contestUser.setSubids(JSONUtil.toJsonStr(subids));
        }

        // 参数校验
        contestUserService.validContestUser(contestUser);

        long id = contestUserUpdateRequest.getId();
        // 判断是否存在
        ContestUser oldContestUser = contestUserService.getById(id);
        ThrowUtils.throwIf(oldContestUser == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = contestUserService.updateById(contestUser);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo/{id}")
    public BaseResponse<ContestUserVO> getContestUserVOById(@PathVariable("id") Long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        ContestUser contestUser = contestUserService.getById(id);
        if (contestUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(contestUserService.getContestUserVO(contestUser));
    }

    @PostMapping("/list")
    public BaseResponse<List<ContestUserVO>> listContestUser() {
        List<ContestUser> contestUserList = contestUserService.list();
        ThrowUtils.throwIf(contestUserList==null, ErrorCode.NOT_FOUND_ERROR, "题目库为空");
        List<ContestUserVO> contestUserVO = contestUserService.getContestUserVO(contestUserList);
        return ResultUtils.success(contestUserVO);
    }

    /**
     * 分页获取列表（仅管理员）
     *
     * @param contestUserQueryRequest
     * @return
     */
   /* @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<ContestUser>> listContestUserByPage(@RequestBody ContestUserQueryRequest contestUserQueryRequest) {
        long current = contestUserQueryRequest.getCurrent();
        long size = contestUserQueryRequest.getPageSize();
        Page<ContestUser> contestUserPage = contestUserService.page(new Page<>(current, size),
                contestUserService.getQueryWrapper(contestUserQueryRequest));
        return ResultUtils.success(contestUserPage);
    }*/

    /**
     * 分页获取列表（封装类）
     *
     * @param contestUserQueryRequest
     * @param request
     * @return
     */
   /* @PostMapping("/list/page/vo")
    public BaseResponse<Page<ContestUserVO>> listContestUserVOByPage(@RequestBody ContestUserQueryRequest contestUserQueryRequest,
            HttpServletRequest request) {
        long current = contestUserQueryRequest.getCurrent();
        long size = contestUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ContestUser> contestUserPage = contestUserService.page(new Page<>(current, size),
                contestUserService.getQueryWrapper(contestUserQueryRequest));
        return ResultUtils.success(contestUserService.getContestUserVOPage(contestUserPage, request));
    }*/

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param contestUserQueryRequest
     * @param request
     * @return
     */
  /*  @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<ContestUserVO>> listMyContestUserVOByPage(@RequestBody ContestUserQueryRequest contestUserQueryRequest,
            HttpServletRequest request) {
        if (contestUserQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        contestUserQueryRequest.setUserId(loginUser.getId());
        long current = contestUserQueryRequest.getCurrent();
        long size = contestUserQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<ContestUser> contestUserPage = contestUserService.page(new Page<>(current, size),
                contestUserService.getQueryWrapper(contestUserQueryRequest));
        return ResultUtils.success(contestUserService.getContestUserVOPage(contestUserPage, request));
    }*/

    // endregion

    /**
     * 修改提交题目信息
     */
    @PutMapping("/updateSubids")
    public BaseResponse<String> updateSubids(@RequestBody ContestUserUpdateSubidsRequest contestUserUpdateSubidsRequest) {
        ThrowUtils.throwIf(contestUserUpdateSubidsRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        Long subid = contestUserUpdateSubidsRequest.getSubid();
        Long contestid = contestUserUpdateSubidsRequest.getContestid();
        Long userid = contestUserUpdateSubidsRequest.getUserid();
        ThrowUtils.throwIf(subid == null || contestid == null || userid != null, ErrorCode.PARAMS_ERROR, "参数为空");
        contestUserService.updateSubids(subid, contestid, userid);
        return ResultUtils.success("更新成功");
    }
    /**
     * 获取用户是否参赛信息
     */
    @GetMapping("/isJoin/{contestid}/{userid}")
    public BaseResponse<Boolean> isJoin(@PathVariable("contestid") Long contestid, @PathVariable("userid") Long userid, HttpServletRequest request) {
        if (contestid == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        contestUserService.isJoin(contestid, userid);
        return ResultUtils.success(true);
    }
    /**
     * 参加比赛
     */
    @PostMapping("/join")
    public BaseResponse<Long> join(@RequestBody ContestUserJoinRequest contestUserJoinRequest) {
        ThrowUtils.throwIf(contestUserJoinRequest == null, ErrorCode.PARAMS_ERROR, "参数为空");
        Long newJoinId = contestUserService.join(contestUserJoinRequest);
        return ResultUtils.success(newJoinId);
    }
}
